iT邦幫忙

0

[C#] Word套版-DocX

  • 分享至 

  • xImage
  •  

1.新增專案
2.載入組件DocX (用NUGET載入)
3.using Xceed.Words.NET;

1.測試1.docx 裡面寫[$t1$],等等把[$t1$]做替換.

private static void 黑大_來源是一個值()
{
    string fileName = @"e:\測試1.docx";
    using (DocX document = DocX.Load(fileName))
    {
        //替换
        document.ReplaceText("[$t1$]", "yayaya"); 
        string fileNamexx = @"e:\測試1_RESULT.docx";
        document.SaveAs(fileNamexx);
    }
}

2.測試2.docx 裡面寫[$today$] [$name$] [$addr$] [$amount$],等等把[$$]做替換.

private static void 黑大2_來源是dictionary()
    {
        string fileName = @"e:\測試2.docx";
        Dictionary<string, string> dct = new Dictionary<string, string>()
        { { "today", DateTime.Today.ToString("yyyy-MM-dd") },
          { "name", "大光頭" },
          { "addr", "幸福" },
          { "amount", "沒賣" } };

        using (DocX document = DocX.Load(fileName))
        {
            foreach (string key in dct.Keys)
            {
                document.ReplaceText("[$" + key + "$]", dct[key]); 
            }

            string fileNamexx = @"e:\測試2_RESULT.docx";
            document.SaveAs(fileNamexx);
        }
    }

3.測試3:來源改成DATATABLE
測試3.docx 裡面寫[$today$] [$name$] [$addr$] [$amount$],等等把[$$]做替換.

using System;
using Xceed.Words.NET;
using System.IO;
private   void 黑大_來源是datatable()
    {
            string tmpFileName = DateTime.Now.ToString("yyyyMMddHHmmssFFF");
            string fileNamexx = @"E:\" + tmpFileName + ".docX";//2 save

        string srcFileName = @"e:\測試3.docx";
        AccessDB AccDB = new AccessDB();
        string strSQL = "select today='t1' ,name='love',addr='金門',amount='3.333'  ";
        AccDB.OpenConnection();
        AccDB.GetDataAdapter(strSQL);
        AccDB.sDataSet = AccDB.GetDataSet();

        AccDB.CloseConnection();

        using (DocX document = DocX.Load(srcFileName))
        {
            foreach (System.Data.DataColumn dc in AccDB.sDataSet.Tables[0].Columns)
            {
                string key = dc.ColumnName;
                document.ReplaceText("[$" + key + "$]", AccDB.sDataSet.Tables[0].Rows[0][key].ToString()); 
            }

            document.SaveAs(fileNamexx);
        }

        byte[] buff = File.ReadAllBytes(fileNamexx);
        File.Delete(fileNamexx);
        Response.Clear();
        Response.ContentType = "application/octet-stream";//word OK            
        Response.AddHeader("content-disposition", "attachment;filename=RESULT.docx");
        Response.BinaryWrite(buff);

        Response.End();  
    }

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言